const Router = require('@koa/router');
const bcrypt = require('bcryptjs');
const { Op } = require('sequelize');
const { User, Comment, Article, sequelize } = require('../databases/index');
const { generateToken } = require('../utils/jwt');


const userRouter = new Router({
    prefix: '/user'
});


userRouter.post('/login', async (ctx) => {
  const { username, password } = ctx.request.body;
  
  // 查找用户
  const user = await User.findOne({ where: { username } });
  if (!user) {
    ctx.status = 401;
    ctx.body = { message: '登录失败，请检查用户名和密码.' };
    return;
  }
  
  // 验证密码
  const validPassword = await bcrypt.compare(password, user.password);
  if (!validPassword) {
    ctx.status = 401;
    ctx.body = { message: '登录失败，请检查用户名和密码.' };
    return;
  }
  
  // 生成JWT token
  const token = generateToken(user);
  
  ctx.body = {
    message: '登录成功',
    token,
    user: {
      id: user.userId,
      username: user.username,
      email: user.email,
      role: user.role
    }
  };
});

userRouter.get('/', async (ctx,next) => {
  const users = await User.findAll();
  console.log(users);
  ctx.body = {
    message: '用户列表',
    data: users
  };
}); 

//增加用户

userRouter.post('/add', async (ctx,next) => {
  // 先对密码进行加密
  const { username, password, email, phone, avatar, role, status } = ctx.request.body;
  const salt = await bcrypt.genSalt(10);
  const hashedPassword = await bcrypt.hash(password, salt);
  
    // 使用加密后的密码创建用户，明确不包含userId
  const currentUser = await User.create({ 
    username, 
    password: hashedPassword, 
    email, 
    phone, 
    avatar, 
    role, 
    status 
  }, {
    fields: ['username', 'password', 'email', 'phone', 'avatar', 'role', 'status'] // 明确指定要插入的字段
  });
  
  ctx.body = {
    message: '用户添加成功',
    data: currentUser
  }
});


//删除用户（级联删除关联的评论和文章）
userRouter.delete('/delete/:id', async (ctx,next) => {
  const { id } = ctx.params;
  
  try {
    // 启动事务
    await sequelize.transaction(async (t) => {
      // 1. 删除用户的评论
      await Comment.destroy({
        where: {
          userId: id
        },
        transaction: t
      });
      
      // 2. 最后删除用户
      await User.destroy({
        where: {
          userId: id
        },
        transaction: t
      });
    });
    
    ctx.body = {
      message: '用户及其关联数据已成功删除',
      data: {
        userId: id
      }
    };
  } catch (error) {
    ctx.status = 500;
    ctx.body = {
      message: '删除用户失败',
      error: error.message
    };
  }
});

//更新用户
userRouter.put('/update/:id', async (ctx,next) => {
  const { id } = ctx.params;
  console.log('更新用户id:', id);
  
  try {
    const { username, password, email, phone, avatar, role, status } = ctx.request.body;
    
    // 先查找当前用户，检查是否存在
    const currentUser = await User.findByPk(id);
    if (!currentUser) {
      ctx.status = 404;
      ctx.body = {
        message: '用户不存在'
      };
      return;
    }
    
    // 创建要更新的数据对象
    const updateData = {
      username,
      phone,
      avatar,
      role,
      status
    };
    
    // 如果提供了密码，则对密码进行加密
    if (password) {
      const hashedPassword = await bcrypt.hash(password, 10);
      updateData.password = hashedPassword;
    }
    
    // 如果email发生了变化，则检查新email是否已被其他用户使用
    if (email && email !== currentUser.email) {
      // 检查email是否已存在
      const existingUser = await User.findOne({
        where: {
          email: email
        }
      });
      
      if (existingUser) {
        ctx.status = 400;
        ctx.body = {
          message: '该邮箱地址已被使用，请更换其他邮箱'
        };
        return;
      }
      
      updateData.email = email;
    }
    
    // 执行更新操作
    await User.update(updateData, {
      where: {
        userId: id
      }
    });
    
    // 获取更新后的用户信息（不包含密码）
    const updatedUser = await User.findByPk(id, {
      attributes: ['userId', 'username', 'email', 'phone', 'avatar', 'role', 'status']
    });
    
    ctx.body = {
      message: '用户信息更新成功',
      data: updatedUser
    };
  } catch (error) {
    console.error('更新用户失败:', error);
    
    // 特殊处理唯一性约束错误
    if (error.name === 'SequelizeUniqueConstraintError') {
      const field = error.fields ? Object.keys(error.fields)[0] : '';
      ctx.status = 400;
      ctx.body = {
        message: `更新失败：${field || '该字段'}已被使用`,
        error: error.message
      };
    } else {
      ctx.status = 500;
      ctx.body = {
        message: '更新用户失败',
        error: error.message
      };
    }
  }
});


//根据名字模糊查询用户
userRouter.get('/name/:username', async (ctx,next) => {
  const { username } = ctx.params;
  const { Op } = require('sequelize');
  const users = await User.findAll({ 
    where: { 
      username: { [Op.like]: `%${username}%` } 
    } 
  });
  if (users.length === 0) {
    ctx.status = 404;
    ctx.body = { message: '没有找到匹配的用户' };
    return;
  }
  ctx.body = {
    message: '查询成功',
    data: users
  };
});

//角色查询
userRouter.get('/role/:role', async (ctx,next) => {
  const { role } = ctx.params;
  const users = await User.findAll({ 
    where: { 
      role 
    } 
  });
  if (users.length === 0) {
    ctx.status = 404;
    ctx.body = { message: '没有找到匹配的用户' };
    return;
  }
  ctx.body = {
    message: '查询成功',
    data: users
  };
});

//状态查询
userRouter.get('/status/:status', async (ctx,next) => {
  const { status } = ctx.params;
  const users = await User.findAll({ 
    where: { 
      status 
    } 
  });
  if (users.length === 0) {
    ctx.status = 404;
    ctx.body = { message: '没有找到匹配的用户' };
    return;
  }
  ctx.body = {
    message: '查询成功',
    data: users
  };
});

//用户表分页 - 返回分页数据和总条数，支持过滤条件
userRouter.get('/page/:page/:size', async (ctx,next) => {
  const { page, size } = ctx.params;
  const { username, role, status } = ctx.query;
  const offset = (page - 1) * size;
  
  // 构建查询条件
  const where = {};
  if (username) {
    where.username = { [Op.like]: `%${username}%` };
  }
  if (role) {
    where.role = role;
  }
  if (status) {
    where.status = parseInt(status);
  }
  
  // 查询分页数据
  const users = await User.findAll({
    where: where,
    offset: parseInt(offset),
    limit: parseInt(size)
  });
  
  // 查询总条数
  const total = await User.count({
    where: where
  });
  
  ctx.body = {
    message: '查询成功',
    data: users,
    total: total
  };
});

//用户总数
userRouter.get('/total', async (ctx,next) => {
  const total = await User.count();
  ctx.body = {
    message: '查询成功',
    total: total
  };
});
 
//最新注册的用户的前5个
userRouter.get('/new', async (ctx,next) => {
  const users = await User.findAll({
    order: [['createdAt', 'DESC']],
    limit: 5,
    attributes: ['userId', 'username', 'email', 'createdAt']
  });
  ctx.body = {
    message: '查询成功',
    data: users
  };
});


module.exports = userRouter;

